import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

// elementName: 需要输出PDF的页面id
// htmlTitle: 页面标题
// currentTime: 当前时间
export default function(elementName, htmlTitle, currentTime) {
  let pdf = new jsPDF('p', 'mm', 'a4') // a4纸 纵向
  let element = document.getElementById(elementName)
  let elementArr = []
  elementArr = Array.from(element.children).filter(child => child.tagName === 'DIV')
  console.log(elementArr, 'elementArr')
  for (let i in elementArr) {
    console.log(elementArr[i], 'elementArr[i]')
    html2canvas(elementArr[i], {
      useCORS: true,
      allowTaint: false,
      logging: false,
      scale: 2,
      dpi: 300
    }).then(function(canvas) {
      let ctx = canvas.getContext('2d')
      let a4w = 190
      let a4h = 277 // a4大小 210mm*297mm 四边保留20mm边距
      // let a4w = 185
      // let a4h = 128 // a4大小  210mm*148mm 四边保留20mm边距
      let imgHeight = Math.floor(a4h * canvas.width / a4w)  // 按a4显示比列换算一页图像的像素高度
      let renderedHeight = 0
      while (renderedHeight < canvas.height) {
        let page = document.createElement('canvas')
        page.width = canvas.width
        page.height = Math.min(imgHeight, canvas.height - renderedHeight) // 可能内容不足一页
      
        // 用getImageData剪裁指定区域，并画到前面创建的canvas对象中
        page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
        pdf.addImage(page.toDataURL('image/jpg', 1.0), 'jpg', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)) // 添加图像到页面，保留10mm边距
        renderedHeight += imgHeight
        if (i < elementArr.length - 1) {
           pdf.addPage()
        }// 如果后面还有内容，添加一个空页
      }
      if (i == elementArr.length - 1) {
        pdf.save(htmlTitle + currentTime)
      }
    })
  }
  return pdf
}
